/**
 * Created by DevilsEyes on 2016/4/21.
 */
'use strict';
var md5 = require('blueimp-md5');

var userId2Session = {};
var ssid2Session = {};

let Disable_Time = 1000 * 60 * 60 * 24 * 7;

class Session {

    refresh() {
        this.disable = new Date().getTime() + Disable_Time;
    }

    constructor(info) {
        if (info === undefined)throw {
            code: 9999,
            msg: 'Session未保存'
        };
        this.id = md5(JSON.stringify(info));
        this.class = info.class;
        this.role = info.role;
        this.md5_userId = md5(info.id);
        this.studentId = info.id;
        this.disable = new Date().getTime() + Disable_Time;
    }
}

var getById = (md5_userId)=> {
    let Se = userId2Session[md5_userId];
    if (Se) {
        Se.refresh();
        return Se;
    } else {
        return null;
    }
};

var getBySid = (ssid)=> {
    let Se = ssid2Session[ssid];
    if (Se) {
        Se.refresh();
        return Se;
    } else {
        return null;
    }
};

var setSession = (user)=> {
    let id = user.id;
    let Se = userId2Session[id];
    if (Se) {
        Se.refresh();
        return Se.id;
    } else {
        Se = new Session(user);
        userId2Session[id] = Se;
        ssid2Session[Se.id] = Se;
        return Se.id;
    }
};

var clearSessionBySsid = (ssid)=> {
    let Se = getBySid(ssid);
    delete userId2Session[Se.md5_userId];
    delete ssid2Session[ssid];
};

var isAdmin = (ssid)=> {
    var Se = getBySid(ssid);
    if (Se && Se.role >= 9999) {
        return true;
    } else {
        throw {
            code: 9999,
            msg: '权限不够'
        }
    }
};

module.exports = {

    setSession: setSession,
    clearSessionBySsid: clearSessionBySsid,
    getById: getById,
    getBySid: getBySid,

    isAdmin: isAdmin

};